<template>
    <div id="detail-model">
        <el-dialog
            :title="titleCon"
            v-model="MdetailDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
        >
            <div style="width: 96%; margin: auto;">
                <template v-for="(item,index) in basicsInfo" :key="index">
                    <template v-if="item.type === 'form'">
                        <el-divider content-position="left">{{ item.formTitle }}</el-divider>  
                        <el-form :model="ruleForm" size="default" :label-width="labelWidth">
                            <el-row>
                                <el-col v-for="(data,index) in Object.keys(item.info)" :key="index" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                                    <el-form-item :label="data">
                                        <el-input disabled readonly v-model="item.info[data]" :placeholder="data" clearable />
                                    </el-form-item>
                                </el-col>
                                <img v-if="imgSrc" style="padding: 0px 0px 10px 10px;" :src="imgSrc" />
                            </el-row>
                        </el-form>
                    </template>
                    <template v-if="item.type === 'table'">
                        <el-divider content-position="left">{{ item.tableTitle }}</el-divider>
                        <el-table :data="item.listData" style="width: 100%" border>
                            <template v-for="(t,key) in item.listData[0]" :key="key">
                                <el-table-column v-if="typeof key === 'string' && key !== 'id' && key !== 'fileObjectName'" :minWidth="item.minWidth" :label="key" :prop="key" :show-overflow-tooltip="true" align="center" />
                            </template>
                            <el-table-column v-if="item.isShowBtn" label="操作" align="center" fixed="right">
                                <template #default="{row}">
                                    <el-button @click="viewClick(row)" class="icon-e" text type="warning">预览</el-button>
                                    <el-button @click="download(row)" class="icon-e" text type="primary">下载</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </template>
            </div>
            <template #footer>
                <el-button @click="cancelUseClick">关 闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRefs , watch } from 'vue';
import { ElButton, ElCol, ElDialog, ElForm, ElRow } from 'element-plus';
import axios  from 'axios';

/*** 定义接口基础数据类型 */
interface formType {
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {}
export default defineComponent( {
    name: 'detail-model',
    components: {},
    props: {
        MdetailDialog:{
            type: Boolean,
            default: false,
        },
        detailInfo: {
            type: Array,
            default: [],
        },
        labelWidth: {
            type: String,
            default: '',
        },
        titleConInfo: {
            type: String,
            default: '',
        },
        imgSrc: {
            type: String,
            default: '',
        },
    },
    setup(props,ctx){
        const titleCon = ref();
        const basicsInfo: any = ref();
        const baseUrl = import.meta.env.VITE_API_URL as any;
    
        const ideView = import.meta.env.VITE_APP_API_VIEW_IDE;
        const base64Url = baseUrl + 'api/sysFileInfo/previewBase64'; // 设备类型接口

       
        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            ruleForm: {} as ruleFormType
        });

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        };

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelDetailClick')
        };

        /*** 监听MdetailDialog的变化 */
        watch(() => props.MdetailDialog,(newVal) => {
            if(newVal){
                titleCon.value = props.titleConInfo ? props.titleConInfo : '详情';
                basicsInfo.value = props.detailInfo;
            }
        });

        // 将Base64编码数据转换为Blob对象的辅助函数
        const base64ToBlob = (base64Data: any) => {
            var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
            var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
            var ab = new ArrayBuffer(byteString.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }
            return new Blob([ab], {type: mimeString});
        }
        
        let isShowFile = false;
        let setInfo: any;
        /*** downClick 下载文件 */
        const download = async (val: any) => {
            console.log(val,'val')
            await getFileFun(val.id);
            // 等待getFileFun完成
            let setTimes = setInterval(() => {
                if(isShowFile){
                    let base64Data = setInfo;
                    let blob = base64ToBlob(base64Data);
                    
                    // 创建可下载的链接
                    let url = URL.createObjectURL(blob);
                    let link = document.createElement('a');
                    link.href = url;
                    link.download = val['附件名称']; // 指定下载的文件名
                    
                    // 将链接添加到DOM中
                    document.body.appendChild(link);
                    
                    // 触发点击事件开始下载
                    link.click();
                    
                    // 释放临时URL
                    URL.revokeObjectURL(url);
                    clearInterval(setTimes);
                }
            },20);
        };

        /*** getFileFun 获取文件数据 */
        const getFileFun = async(val: Number) => {
            let param: any = {};
            param.id = val;
            axios.get(base64Url,{ params: param }).then((res: any) => {
                let item = res.data;
                if(item.success){
                    isShowFile = true;
                    setInfo = item.data;
                }
            }).catch((error: any) => {
                console.error('请求错误', error)
            });
        }

        /*** MdetailDialog 响应弹窗的关闭  */
        const MdetailDialog = computed(() => {
            return props.MdetailDialog
        });

        /*** 预览 */
        const viewClick = (val: any) => {
            let viewUrl = baseUrl + 'api/Upload' + ideView + val.fileObjectName;
            window.open(viewUrl);
        }

        return {
            handleClose,
            cancelUseClick,
            titleCon,
            ...toRefs(state),
            MdetailDialog,
            basicsInfo,
            download,
            viewClick,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-dialog__body){
    height: auto !important;
    max-height: 60vh !important;
    overflow-y: auto;
}
:deep(.el-overlay){
    .el-overlay-dialog{
        .el-dialog{
            .el-dialog__body{
                padding: 0px !important;
            }
        }
    }
} 
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
:deep(.el-input__wrapper){
    width: 100%; 
}
</style>